package com.ht.file.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ht.common.core.exception.ServiceException;
import com.ht.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
public class FileCheckService {
    /**
     * 最大的文件长度
     */
    @Value("${file.upload.maxSize}")
    private String maxSize;
    private int maxSizeInt = 10 * 1024;
    /**
     * 允许文件类型
     */
    @Value("${file.upload.extFile}")
    private String extFile;
    private List<String> extFiles = new ArrayList<String>();


    public void checkFileLegal(MultipartFile file) {
        initExtFiles();
        String contentType = file.getOriginalFilename().toLowerCase();
        String fileExtName = FileUtil.extName(contentType);
        if (StringUtils.isEmpty(extFiles)) {
            throw new ServiceException("不允许上传文件!");
        }
        if (file.isEmpty() || !extFiles.contains(fileExtName)) {
            throw new ServiceException("非法格式或空文件");
        }
        Double fileSize = file.getSize() / 1024d;
        if (fileSize > maxSizeInt) {
            throw new ServiceException(StrUtil.format("最大允许上传 {} KB", (maxSizeInt)));
        }
    }

    public void checkFileLegal(String fileName, Double flen) {
        initExtFiles();
        if (null == fileName) {
            throw new ServiceException("非法格式或空文件");
        }
        String contentType = FileUtil.extName(fileName).toLowerCase();
        String fileExtName = FileUtil.extName(contentType);
        if (StringUtils.isEmpty(extFiles)) {
            throw new ServiceException("不允许上传文件!");
        }
        if (0 == flen || !extFiles.contains(fileExtName)) {
            throw new ServiceException("非法格式或空文件");
        }
        if (flen > maxSizeInt) {
            throw new ServiceException(StrUtil.format("最大允许上传 {} KB", (maxSizeInt / 1000)));
        }
    }


    private void initExtFiles() {
        if (null != extFile && extFile.trim().length() > 0) {
            extFiles = StringUtils.stringToList(extFile, ",");
        } else {
            extFiles.clear();
        }
        if (null != maxSize) {
            try {
                maxSizeInt = Integer.parseInt(maxSize);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        } else {
            maxSizeInt = 1024;
        }
    }


}
